package com.ls.server.controller;

import com.ls.server.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload.path:/upload}")
    private String uploadPath;

    @Value("${file.access.path:/files}")
    private String accessPath;

    /**
     * 上传图片
     * @param file 图片文件
     * @return 图片访问URL
     */
    @PostMapping("/upload/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传的文件不能为空");
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 构建文件保存路径
        String fileName = UUID.randomUUID().toString().replace("-", "") + extension;
        String today = java.time.LocalDate.now().toString();
        String relativePath = "/images/" + today + "/" + fileName;
        String absolutePath = uploadPath + relativePath;

        try {
            // 确保目录存在
            Path dirPath = Paths.get(absolutePath).getParent();
            if (dirPath != null && !Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }

            // 保存文件
            file.transferTo(new File(absolutePath));
            logger.info("文件上传成功: {}", absolutePath);

            // 返回文件访问路径
            return Result.success(accessPath + relativePath);
        } catch (IOException e) {
            logger.error("文件上传失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
} 